﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.CodeDom.Compiler;
using ObjectBakery.Interfaces;


namespace ObjectBakery
{
    public class ScriptProxy : MarshalByRefObject, IObjectProxy
    {

        public static ScriptObjectFactory objectFactory;

        private readonly Type proxiedType;

        private readonly object proxiedObject;

        public object ProxiedObject
        {
            get { return proxiedObject; }
        }


        //TODO: Change ctor to take a factory or builder
        public ScriptProxy(string strTypeName, string strSource, Language language)  
        {
            if (objectFactory == null)
                objectFactory = new ScriptObjectFactory(language);
            
            var instances = objectFactory.Build(new List<string>(new string[] { strTypeName }), strSource);
           

            //TODO: Look at delegating the ring management to runner.. and do single in here..
            proxiedObject = instances[0];
            proxiedType = proxiedObject.GetType();
        }



        public object InvokeMethod(string strMethodName, object[] parameters)
        {
           
            return proxiedType.InvokeMember(strMethodName,
                                              BindingFlags.InvokeMethod,
                                              null,
                                              proxiedObject,
                                              parameters);
        }



        
        
        public object GetProperty(string propertyName)
        {

            System.Reflection.PropertyInfo myProperty = proxiedType.GetProperty(propertyName);
            return myProperty.GetValue(proxiedObject, null);

        }

        public void SetProperty(string propertyName, object value)
        {

            System.Reflection.PropertyInfo myProperty = proxiedType.GetProperty(propertyName);
            myProperty.SetValue(proxiedObject, value, null);

        }
    
    
    }
}
